package com.googlecode.allinclusive.fw.springframework.server;

import java.util.Timer;
import java.util.TimerTask;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/*
 * class TimerServer {
 * 		long interval;
 * 		long delay;
 * 		Processor processor;
 * }
 * 
 * <bean id="***Timer" class="package.TimerServer">
 * 		<property="processor" ref="***Processor"/>
 * </bean>
 */
public abstract class Server {

	private static final Log log = LogFactory.getLog(Server.class);
	
	/*
	 * 1 : injected from spring configuration file.
	 * 2 : GlobalConfig.getProperty(this.getClass().getName() + ".interval") 
	 */
	private long interval = 60000l;
	
	private long delay = 0l;
	
	private Timer timer;
	
	/**
	 * Start Server.
	 */
	@PostConstruct
	public void init() {
		log.info(this.getClass().getSimpleName() + " start...");
		TimerTask t = new TimerTask() {
			public void run() {
				try {
					// process
					process();
				} catch (Throwable th) {
					// ignore
					log.warn(th.getMessage(), th);
				}
			}
		};
		
		timer = new Timer();
		timer.schedule(t, delay, interval);
	}
	
	/**
	 * Stop Server.
	 */
	@PreDestroy
	public void destroy() {
		log.info(this.getClass().getSimpleName() + " stop...");
		if (timer != null) {
			timer.cancel();
		}
	}
	
	protected abstract void process();

	public void setInterval(long interval) {
		this.interval = interval;
	}
	
	public void setDelay(long delay) {
		this.delay = delay;
	}
}
